package com.eras.shoes.ui

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.le.ScanResult
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.eras.shoes.R
import com.eras.shoes.adapter.DeviceAdapter
import com.eras.shoes.contents.Api
import com.eras.shoes.contents.BindShoes
import com.eras.shoes.contents.BleBean
import com.eras.shoes.contents.BleDataEx
import com.eras.shoes.contents.BluetoothDeviceWithRssi
import com.eras.shoes.contents.Global
import com.eras.shoes.contents.MessageCallBack
import com.eras.shoes.contents.MessageEvent
import com.eras.shoes.databinding.ActivityBindBinding
import com.eras.shoes.db.MacBlacklistManager
import com.eras.shoes.utils.BluetoothController
import com.eras.shoes.utils.BluetoothService
import com.eras.shoes.utils.DimensUtil
import com.eras.shoes.utils.OkHttpUtils
import com.eras.shoes.utils.ToastUtils
import com.eras.shoes.view.RxDialogBindLightSureCancel
import com.eras.shoes.view.RxDialogBindSureCancel
import com.eras.shoes.view.popupdialog.PopupSheet
import com.eras.shoes.view.popupdialog.PopupSheetCallback
import com.google.gson.Gson
import com.google.zxing.integration.android.IntentIntegrator
import com.google.zxing.integration.android.IntentResult
import okhttp3.Request
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.io.IOException
import java.text.MessageFormat
import java.util.Arrays
import java.util.Objects


@Suppress("UNREACHABLE_CODE")
class BindActivity : ComponentActivity(), View.OnClickListener {
    private val PERMISSIONS_REQUEST_CODE = 101
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.BLUETOOTH,
        Manifest.permission.BLUETOOTH_ADMIN,
        Manifest.permission.ACCESS_FINE_LOCATION
    )
    private val sharedPref by lazy {
        getSharedPreferences("login_prefs", Context.MODE_PRIVATE)
    }
    private lateinit var bluetoothService: BluetoothService

    private var broadcastReceiver: CalibrateActivity.BtTemperatureReceiver? = null

    // 蓝牙核心组件
    private val foundDevices = mutableListOf<BleBean>()
    private lateinit var connectedBean: BleBean
    private val bluetoothController = BluetoothController.getInstance()
    private val deviceList = mutableListOf<ScanResult>()
    private var shoesName: String = ""//蓝牙鞋
    private var serialNumber: String = ""//序列号
    private var shoeSex: Int = -1//鞋性别
    private var footType: String = ""//鞋子类别
    private var shoesSize: String = ""//鞋子大小
//    private var shoesMac: String = ""//蓝牙鞋mac
    private lateinit var manager: MacBlacklistManager
    private var currentRssiThreshold = -40 // 默认功率阈值
    private var connectDevice: BleBean = BleBean() //连接成功的设备
    // 在Activity中初始化适配器
    @SuppressLint("MissingPermission")
    private val adapter = DeviceAdapter { device ->
        connectToDevice(device)
    }
    private lateinit var binding: ActivityBindBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        binding = ActivityBindBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.tvBindBack.setOnClickListener(this)
        binding.tvBindRssiIdFour.setOnClickListener(this)
        binding.tvBindRssiIdFive.setOnClickListener(this)
        binding.tvBindRssiIdSix.setOnClickListener(this)
        binding.tvBindRssiIdSeven.setOnClickListener(this)
        binding.btnBindScanCode.setOnClickListener(this)
        binding.tvBindRefresh.setOnClickListener(this)
        binding.tvBindShoesSize.setOnClickListener(this)
        binding.radioBindFemale.setOnClickListener(this)
        binding.radioBindMale.setOnClickListener(this)
        binding.radioBindLeft.setOnClickListener(this)
        binding.radioBindRight.setOnClickListener(this)
        binding.btnBindSubmit.setOnClickListener(this)

        manager = MacBlacklistManager(this@BindActivity);

//        // 接收基本数据类型
//        shoesSize = intent.getStringExtra("SHOES_SIZE_KEY").toString()
//        shoeSex = intent.getIntExtra("SHOES_SEX_KEY", 0)
//        if (shoeSex == 0) {
//            binding.radioBindMale.isChecked = true
//            binding.radioBindFemale.isChecked = false
//        } else if (shoeSex == 1) {
//            binding.radioBindMale.isChecked = false
//            binding.radioBindFemale.isChecked = true
//        }
//        binding.tvBindShoesSize.text = shoesSize

        binding.btnBindScanCode.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.btnBindScanCode.isEnabled = false
        binding.btnBindSubmit.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.btnBindSubmit.isEnabled = false
    }

    override fun onStart() {
        super.onStart()
        val savedUsername = sharedPref.getString("username", "")
        binding.tvBindBack.text = savedUsername
        bluetoothService = BluetoothService(this)

        binding.rvBindBt.apply {
            layoutManager = LinearLayoutManager(this@BindActivity)
            adapter = this@BindActivity.adapter
            addItemDecoration(
                DividerItemDecoration(
                    this@BindActivity,
                    LinearLayoutManager.VERTICAL
                )
            )
        }
        bluetoothController.initBle(this)
        // 检查权限
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE)
        } else {
            initBtState()
        }
    }

    /**
     * 初始化蓝牙状态广播监听
     */
    private fun initBtState() {
        if (bluetoothController.isBleOpen) {
            bluetoothController.startScanBle()
        } else {
            bluetoothController.initBle(this)
        }
    }

    @SuppressLint("MissingPermission", "NotifyDataSetChanged")
    private fun connectToDevice(device: BleBean) {
        if(Global.connectState == 1) {
            ToastUtils().show(this@BindActivity, "有设备正在连接中...")
            return
        }
        if (BluetoothController.macAddress == null) {
            device.connectState = 0
            Global.connectType = 0
            Global.address = device.address
            adapter.notifyDataSetChanged()
            bluetoothController.connect(device.address)
            return
        }
        if (BluetoothController.macAddress != null && BluetoothController.macAddress.equals(device.address)) {
            ToastUtils().show(this@BindActivity, "该设备已连接")
            return
        }
        if (BluetoothController.macAddress != null) {
            bluetoothController.closeBuletooth(BluetoothController.macAddress)
            device.connectState = 0
            Global.connectType = 0
            Global.address = device.address
            adapter.notifyDataSetChanged()
            bluetoothController.connect(device.address)
        }


        Log.e("CalibrateActivity", "正在连接: ${device.name}")
    }

    // 通过对象内容删除
    fun <T> removeByItem(list: MutableList<T>, item: T): Boolean {
        return list.remove(item)
    }

    private fun updateDeviceList(device: BluetoothDeviceWithRssi) {
        val existingIndex = foundDevices.indexOfFirst {
            it.address == device.bean.address
        }
        if (existingIndex >= 0) {
            foundDevices[existingIndex] = device.bean
        } else {
            foundDevices.add(device.bean)
        }
        foundDevices.sortByDescending { device.bean.rssi } // 按value降序排序
        adapter.submitList(foundDevices.toList())
    }

    // 处理主线程事件（默认模式）
    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent<*>) {
        var bleBeans: BleBean
        when (event.getAction()) {
            MessageEvent.ACTION_GATT_CONNECTED -> {
                Global.connectState = 2
                Global.isConnected = true
                bleBeans = event.data as BleBean
                for (i in 0 until foundDevices.size) {
                    val bleBean: BleBean = foundDevices.get(i)
                    if (bleBean.address.equals(bleBeans.address)) {
                        bleBean.connectState = 1
                        bleBeans = bleBean
                    }
                }
                adapter.notifyDataSetChanged()
                connectSuccess(bleBeans)
            }

            MessageEvent.ACTION_GATT_DISCONNECTED -> {
                val address = event.data as String
                Global.connectState = 0
                Global.isConnected = false
                Global.connectType = -1
                Global.address = null
                BluetoothController.macAddress = null
                for (i in 0 until foundDevices.size) {
                    val bleBean: BleBean = foundDevices.get(i)
                    if (bleBean.address.equals(address)) {
                        bleBean.connectState = -1
                    }
                }
                adapter.notifyDataSetChanged()
            }

            MessageEvent.BLE_SCAN_RESULT -> {
//                Log.i("BindActivity", "BLE_SCAN_RESULT :" + event.data.toString())
                // 添加蓝牙
                addBluetooth(event.data as ScanResult)
            }

            MessageEvent.EVENT_DEVICE_COLL_BACK -> {
                Log.i("BindActivity", "EVENT_DEVICE_COLL_BACK :" + event.data)
                val strRecvTxt = java.lang.String.valueOf(event.data)
                if (strRecvTxt.length > 1) {
                    val gson: Gson = Gson()
                    val messageCallBack: MessageCallBack =
                        gson.fromJson(strRecvTxt, MessageCallBack::class.java)
                    val message = Message()
                    message.obj = messageCallBack.msg
                    message.arg1 = 1
//                    handlerSetText.sendMessage(message)
                }
            }
//            MessageEvent.SMART_SHOES_BLUETOOTH_DATA -> {
//                val ldata: SmartShoesWebBean = event.data as SmartShoesWebBean
//                zcm.setLeftData(ldata.getBulDate())
//            }

        }
    }

    @SuppressLint("MissingPermission")
    private fun addBluetooth(result: ScanResult) {
        if (manager.isBlacklisted(result.device.address)) {
            return
        }
        if (currentRssiThreshold >= result.rssi) {
            return
        }
        this.runOnUiThread(Runnable {
            if (!deviceList.any { it.device.address == result.device.address }) {
                deviceList.add(result)
                val bytes = result.scanRecord!!.bytes
                val serialNumber = BleDataEx.getStringValue(bytes, 17, 9)
                val bean =
                    BleBean(
                        result.device.name,
                        result.device.address,
                        result.rssi,
                        serialNumber
                    )
                updateDeviceList(BluetoothDeviceWithRssi(bean, result.rssi))
            }
        })
    }

    @SuppressLint("MissingPermission")
    private fun connectSuccess(data: BleBean) {
        connectDevice = data
        this.runOnUiThread(Runnable {
            val name = data.name
            shoesName = name

            val address = data.address
            BluetoothController.macAddress = address
//            shoesMac = address
            binding.btnBindScanCode.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.btnBindScanCode.isEnabled = true
        })
    }


    override fun onResume() {
        super.onResume()
        if (!EventBus.getDefault().isRegistered(this)) { //加上判断
            EventBus.getDefault().register(this)
        }
        broadcastReceiver = CalibrateActivity.BtTemperatureReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(broadcastReceiver, intentFilter)
    }

    override fun onPause() {
        super.onPause()
        EventBus.getDefault().unregister(this)
        unregisterReceiver(broadcastReceiver) //注销广播接收器
    }

    override fun onDestroy() {
        super.onDestroy()
        bluetoothController.stopScanBle()
    }

    /**
     * 蓝牙状态广播回调
     */
    internal class BtTemperatureReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            //注意!这里是先拿action 等于 BluetoothAdapter.ACTION_STATE_CHANGED 在解析intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
            if (BluetoothAdapter.ACTION_STATE_CHANGED == Objects.requireNonNull<String?>(action)) {
                val blState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
                when (blState) {
                    BluetoothAdapter.STATE_TURNING_ON -> {
                    }

                    BluetoothAdapter.STATE_ON ->
//                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙开启成功");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙开启成功",Toast.LENGTH_SHORT).show();
                    {
                        BluetoothController.getInstance().startScanBle()
                    }

                    BluetoothAdapter.STATE_TURNING_OFF -> //                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙正在关闭中……，请稍等");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙正在关闭中……，请稍等",Toast.LENGTH_SHORT).show();
                    {

                    }

                    BluetoothAdapter.STATE_OFF -> {
                        //                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙已关闭");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙已关闭",Toast.LENGTH_SHORT).show();
                    }

                    BluetoothAdapter.ERROR -> {

                    }

                    else -> {}
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result: IntentResult? =
            IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents != null) {
                // 扫描结果，result.contents是二维码内容
                val qrCodeContent = result.contents
                serialNumber = qrCodeContent
                binding.tvBindSerialNumber.setText(qrCodeContent)
                Log.e("BindActivity", "qrCodeContent=" + qrCodeContent)
                binding.btnBindSubmit.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.btnBindSubmit.isEnabled = true
//                ToastUtils().show(this, "qrCodeContent=" + qrCodeContent)
                // 这里可以添加HTTP请求获取数据的代码
                // 例如使用kotlinx.coroutines或者其他网络库发起请求
            } else {
                // 扫描失败
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun selectBlueRssiId(view: TextView, arrays: Array<String>) {
        val popupSheet: PopupSheet
        val arrayList = Arrays.asList(*arrays)
        popupSheet =
            PopupSheet(this@BindActivity, view, arrayList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@BindActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", arrayList[position])
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    view.text = arrayList[position].toString()
                    when (arrayList[position]) {
                        "-40dB" -> {
                            currentRssiThreshold = -40
                        }

                        "-50dB" -> {
                            currentRssiThreshold = -50
                        }

                        "-60dB" -> {
                            currentRssiThreshold = -60
                        }
                        "-70dB" -> {
                            currentRssiThreshold = -70
                        }
                    }
                    foundDevices.clear()
                    deviceList.clear()
                    adapter.submitList(emptyList())
                    if (connectDevice.address != null){
                        foundDevices.add(connectDevice)
                    }
                    bluetoothController.startScanBle()
                }
            }, DimensUtil.dp2px(this@BindActivity, 140F))
        popupSheet.show()
    }

    private fun selectShoesSize(tvShoesSize: TextView, arrayShoesSize: Array<String>) {
        val popupSheet: PopupSheet
        val showSizeList = Arrays.asList(*arrayShoesSize)
        popupSheet =
            PopupSheet(this@BindActivity, tvShoesSize, showSizeList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@BindActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", showSizeList[position])
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    shoesSize = showSizeList[position].toString()
                    tvShoesSize.text = shoesSize
//                    ToastUtils().show(this@BindActivity, "你选择了"+shoesSize+"码")
//                    tvShoesSize.text = MessageFormat.format("{0}", "鞋子尺码：$shoesSize")
                }
            }, DimensUtil.dp2px(this@BindActivity, 140F))
        popupSheet.show()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        disConnected()
        finish()
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_bind_back -> {
                disConnected()
                finish()
            }

            R.id.tv_bind_refresh -> {
                foundDevices.clear()
                deviceList.clear()
                adapter.submitList(emptyList())
                if (connectDevice.address != null){
                    foundDevices.add(connectDevice)
                }
                bluetoothController.startScanBle()
            }

            R.id.tv_bind_rssi_id_four -> {
                reSetRissbg("-40")
                binding.tvBindRssiIdFour.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvBindRssiIdFour.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.white))
            }
            R.id.tv_bind_rssi_id_five -> {
                reSetRissbg("-50")
                binding.tvBindRssiIdFive.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvBindRssiIdFive.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.white))
            }
            R.id.tv_bind_rssi_id_six -> {
                reSetRissbg("-60")
                binding.tvBindRssiIdSix.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvBindRssiIdSix.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.white))
            }
            R.id.tv_bind_rssi_id_seven -> {
                reSetRissbg("-70")
                binding.tvBindRssiIdSeven.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvBindRssiIdSeven.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.white))
            }

            R.id.btn_bind_scan_code -> {
                if (BluetoothController.macAddress == null) {
                    ToastUtils().show(this@BindActivity, "请先连接蓝牙鞋")
                    return
                }
                val rxDialogSureCancel: RxDialogBindLightSureCancel =
                    RxDialogBindLightSureCancel(this@BindActivity)
                rxDialogSureCancel.setCancelListener(View.OnClickListener {
                    disConnected()
                    bluetoothController.startScanBle()
                    rxDialogSureCancel.cancel()
                })
                rxDialogSureCancel.setSureListener(View.OnClickListener {
                    rxDialogSureCancel.cancel()
                    // 扫描二维码
                    IntentIntegrator(this@BindActivity)
                        .setCaptureActivity(PortraitCaptureActivity::class.java)
                        .initiateScan()
                })
                rxDialogSureCancel.show()
            }

            R.id.tv_bind_shoes_size -> {
//                val arrayShoesSize: Array<String> = resources.getStringArray(R.array.shoe_size_list_xz)
//                selectShoesSize(binding.tvBindShoesSize, arrayShoesSize)
            }

            R.id.radio_bind_Male -> {
                binding.radioBindMale.isChecked = true
                binding.radioBindFemale.isChecked = false
                shoeSex = 0
                ToastUtils().show(this, "选择了：男鞋")
            }

            R.id.radio_bind_Female -> {
                binding.radioBindMale.isChecked = false
                binding.radioBindFemale.isChecked = true
                shoeSex = 1
                ToastUtils().show(this, "选择了：女鞋")
            }

            R.id.radio_bind_left -> {
                binding.radioBindLeft.isChecked = true
                binding.radioBindRight.isChecked = false
                footType = "LEFT"
                ToastUtils().show(this, "选择了：左脚")
            }

            R.id.radio_bind_right -> {
                binding.radioBindLeft.isChecked = false
                binding.radioBindRight.isChecked = true
                footType = "RIGHT"
                ToastUtils().show(this, "选择了：右脚")
            }

            R.id.btn_bind_submit -> {
                if (Global.isConnected) {
                    if (BluetoothController.macAddress == null) {
                        ToastUtils().show(this@BindActivity, "mac地址不能为空")
                        return
                    }
                    if (serialNumber.equals("")){
                        ToastUtils().show(this@BindActivity, "序列号不能为空")
                        return
                    }
                    binding.pbLoadingBindSave.visibility = View.VISIBLE
                    bindShoes(BluetoothController.macAddress, serialNumber)
                } else {
                    ToastUtils().show(this@BindActivity, "请先连接蓝牙主板")
                }
            }

        }
    }
    var count: Int = 5

    private fun bindShoes(
        mac: String,
        shoeSn: String,
    ) {
//        shoes.shoeSex = shoeSex
//        shoes.shoeSize = shoeSize
//        shoes.footType = footType
        val shoes = BindShoes("", "")
        shoes.mac = mac
        shoes.shoeSn = shoeSn
        val data = Gson().toJson(shoes)
        OkHttpUtils.postJsonAsync(
            this@BindActivity,
            Api.bindShoes,
            data,
            object : OkHttpUtils.DataCallBack {
                override fun requestFailure(request: Request, e: IOException) {
                    Log.e("BindActivity", "保存失败")
                    if (count >= 0) {
                        count--
                        bindShoes(mac, shoeSn)
                    } else {
                        binding.pbLoadingBindSave.visibility = View.GONE
                        ToastUtils().show(this@BindActivity, "保存失败，请检查网络重试")
                    }
                }

                @Throws(Exception::class)
                override fun requestSuccess(result: String) {
                    binding.pbLoadingBindSave.visibility = View.GONE
                    count = 5
                    val toJsonObj = JSONObject(result)
                    Log.e("BindActivity", "上传返回" + toJsonObj)
                    val code = toJsonObj.getInt("code")
                    if (code == 0) {
                        manager.addToBlacklist(mac)
                        disConnected()
                        bluetoothController.startScanBle()
                        val message = toJsonObj["message"] as String
                        ToastUtils().show(this@BindActivity, "保存" + message)
                    } else {
                        val message = toJsonObj["message"] as String
                        ToastUtils().show(this@BindActivity, message)
                    }
                }
            })

    }

    private fun disConnected() {
        reSetValue()
        Global.address = null
        Global.connectType = -1
        foundDevices.clear()
        deviceList.clear()
        adapter.submitList(emptyList())
        adapter.notifyDataSetChanged()
        if (BluetoothController.macAddress != null) {
            bluetoothController.closeBuletooth(BluetoothController.macAddress)
        }
        bluetoothController.stopScanBle()
    }

    private fun reSetValue() {
        binding.btnBindScanCode.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.btnBindScanCode.isEnabled = false
        binding.btnBindSubmit.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.btnBindSubmit.isEnabled = false
        binding.radioBindLeft.isChecked = false
        binding.radioBindRight.isChecked = false
        footType = ""
        binding.tvBindSerialNumber.text = ""
    }

    private fun reSetRissbg(riss: String) {
        binding.tvBindRssiIdFour.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.black))
        binding.tvBindRssiIdFour.setBackgroundResource(R.drawable.bg_black_frame_btn)

        binding.tvBindRssiIdFive.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.black))
        binding.tvBindRssiIdFive.setBackgroundResource(R.drawable.bg_black_frame_btn)

        binding.tvBindRssiIdSix.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.black))
        binding.tvBindRssiIdSix.setBackgroundResource(R.drawable.bg_black_frame_btn)

        binding.tvBindRssiIdSeven.setTextColor(ContextCompat.getColor(this@BindActivity, R.color.black))
        binding.tvBindRssiIdSeven.setBackgroundResource(R.drawable.bg_black_frame_btn)

        when (riss) {
            "-40" -> {
                currentRssiThreshold = -40
            }

            "-50" -> {
                currentRssiThreshold = -50
            }

            "-60" -> {
                currentRssiThreshold = -60
            }
            "-70" -> {
                currentRssiThreshold = -70
            }
        }
        foundDevices.clear()
        deviceList.clear()
        adapter.submitList(emptyList())
        if (connectDevice.address != null){
            foundDevices.add(connectDevice)
        }
        bluetoothController.startScanBle()
    }


}